package com.entrogy.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.entrogy.bean.Msg;
import com.entrogy.bean.StudentEntity;
import com.entrogy.bean.StudentIcEntity;
import com.entrogy.service.IcCardService;
import com.entrogy.service.SchoolService;
import com.entrogy.service.StudentService;
import com.entrogy.timing.TimingTaskService;
import com.entrogy.utils.EasyExcelUtil;
import com.entrogy.utils.StrUtils;
import com.entrogy.utils.THDio;
import com.entrogy.utils.constants.ErrorEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName IcCardController
 * @Description
 * @Author luoxingjiang
 * @Date 2019-11-02 上午 10:32
 * @Version 1.0
 **/
@RestController
@RequestMapping("/ic-card-manager")
@Api(description = "IC卡管理控制层")
public class IcCardController {

    private static final Logger logger = LoggerFactory.getLogger(IcCardController.class);

    @Autowired
    private IcCardService icCardService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private EasyExcelUtil easyExcelUtil;

    @ApiOperation(value = "批量录入学生的IC卡信息")
    @PutMapping(value = "/student-batchBind-icCard")
    public Msg studentBindIcCard(@RequestBody List<StudentIcEntity> stuIcCardList){
        Integer schoolCode = (Integer) SecurityUtils.getSubject().getSession().getAttribute("schoolCode");
        List<StudentIcEntity> failBindStudentList = icCardService.bindStuCard(stuIcCardList, schoolCode);
        return Msg.success().add("failBindStudentList", failBindStudentList);
    }

    @ApiOperation(value = "单个录入学生的IC卡信息")
    @PutMapping(value = "/student-singleBind-icCard")
    public Msg studentBindIcCard(@RequestBody StudentIcEntity studentIcEntity){
        StudentEntity studentEntity = new StudentEntity();
        studentEntity.setId(studentIcEntity.getStudentId());
        studentEntity.setIcNumber(studentIcEntity.getIcCardNumber());
        String icCardNumber = studentIcEntity.getIcCardNumber();
        // 绑定该张IC卡时，需要判断该IC卡是否已经绑定
        List<StudentEntity> studentFormDbByIcCard = studentService.listSchoolAllStudent(null, null, null, null, null, icCardNumber, null);
        if (studentFormDbByIcCard.size() > 0){
            return Msg.fail(ErrorEnum.E_101, "IC卡号为=>" + icCardNumber + "重复绑定，该生绑定失败！");
        }
        int updateStudentRow = studentService.updateStudent(studentEntity);
        return Msg.success();
    }

    @ApiOperation(value = "导出IC卡录入模板")
    @GetMapping(value = "/export-student-icCard")
    public void exportStudentIcCard(HttpServletRequest request, HttpServletResponse response){
        Integer schoolCode = (Integer) SecurityUtils.getSubject().getSession().getAttribute("schoolCode");
        String parameter1 = request.getParameter("gradeId");
        String parameter2 = request.getParameter("classId");
        Integer gradeId = StringUtils.isNoneBlank(parameter1) ? Integer.valueOf(parameter1) : null;
        Integer classId = StringUtils.isNoneBlank(parameter2) ? Integer.valueOf(parameter2) : null;
        // 是否查询已绑定IC卡的学生名单，0查询未绑定，1查询已绑定，不填查询全部
        Integer isBind = 0;
        List<StudentIcEntity> studentIcList = studentService.listStudentForIcManager(schoolCode, isBind, gradeId, classId, null);
        try (OutputStream out = response.getOutputStream()) {
            try {
                response.setContentType("multipart/form-data");
                response.setCharacterEncoding("utf-8");
                String fileName = URLEncoder.encode("学生IC卡信息表","utf-8");
                response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
                ExcelWriter excelWriter = EasyExcel.write(out, StudentIcEntity.class).build();
                WriteSheet writeSheet = EasyExcel.writerSheet("sheet1").build();
                excelWriter.write(studentIcList, writeSheet);
                excelWriter.finish();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @ApiOperation(value = "批量导入学生的IC卡信息")
    @PostMapping(value = "/student-import-icCard")
    public Msg studentImportIcCard(@RequestParam("excelFile") MultipartFile excelFile){
        logger.info("正在进行学生的IC卡信息excel导入。。。");
        List<StudentEntity> failBindStudentList = new ArrayList<>();
        try {
            failBindStudentList = easyExcelUtil.resolveExcelWithStudentIcCard(excelFile.getInputStream(), studentService);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Msg.success().add("failBindStudentList", failBindStudentList);
    }






}
